package top.ply.authservice.service.impl;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.messaging.Message;
import org.springframework.messaging.MessageChannel;
import org.springframework.messaging.support.MessageBuilder;
import org.springframework.stereotype.Service;
import top.ply.authservice.mq.UserLoginEventQueue;

import java.util.Map;

@Service("wechatAuthService")
public class WechatAuthServiceImpl {

    @Autowired
    @Qualifier("wechatLoginWorker")
    WechatLoginWorkerImpl wechatLoginWorker;

    @Autowired
    UserLoginEventQueue queue;

    public boolean verifyToken(String token) {
        return wechatLoginWorker.verifyToken(token);
    }

    public String getUserIDFromToken(String token) {
        return wechatLoginWorker.getUserIDFromToken(token);
    }

    public boolean accountIsNormal(String userID) {
        return wechatLoginWorker.accountIsNormal(userID);
    }

    public String wechatUserLogin(String js_code) {
        String token = wechatLoginWorker.wechatUserLogin(js_code);
        new Thread(() -> {
            if (token != null) {
                String userID = wechatLoginWorker.getUserIDFromToken(token);
                MessageChannel channel = queue.wechatUserLoginEventOutput();
                Message<String> message = MessageBuilder.withPayload(userID).build();
                channel.send(message);
            }
        }).start();
        return token;
    }

    public Integer getFailReason() {
        return wechatLoginWorker.getFailReason() == null ? 0 : wechatLoginWorker.getFailReason();
    }

}
